const Router = require("koa-router");

const { AdminRegisterValidator } = require("../../validators/admin");
const { Admin } = require("@models/admin");
const { Auth } = require("@middlewares/auth");
const { generateToken } = require("../../../core/util");
const { Alioss } = require("@services/alioss");
//  创建超级管理员
Admin.afterSync(async () => {
  const admin = await Admin.findOne({
    where: { email: "610363806@qq.com" },
  });
  if (!admin) {
    await Admin.create({
      account: "admin",
      admin_name: "超级管理员",
      email: "610363806@qq.com",
      password: "123456",
      power: 32,
    });
  }
});

const router = new Router({
  prefix: "/admin",
});

// 管理员注册
router.post("/register", new Auth(32).m, async (ctx) => {
  const { avatar } = ctx.request.body;
  const v = await new AdminRegisterValidator().validate(ctx);
  const admin = {
    account: v.get("body.account"),
    email: v.get("body.email"),
    password: v.get("body.password2"),
    phone: v.get("body.phone"),
    admin_name: v.get("body.admin_name"),
    avatar,
    power: 16,
  };

  await Admin.create(admin);

  ctx.body = {
    code: 200,
    msg: "创建成功",
  };
});

// 管理员登录
router.post("/login", async (ctx) => {
  const { account, secret } = ctx.request.body;
  const admin = await Admin.verifyEmailPassword(account, secret);

  // 发布令牌
  const token = generateToken(admin.admin_id, admin.power);
  const { password, ...admin_info } = JSON.parse(JSON.stringify(admin));
  ctx.body = {
    code: 200,
    msg: "获取成功",
    data: {
      token: token,
      admin: admin_info,
    },
  };
});

// 获取管理员信息
router.get("/get_info", new Auth(32).m, async (ctx) => {
  userInfo = await Admin.findOne({
    where: {
      id: ctx.auth.uid,
    },
  });

  if (!userInfo) {
    throw new global.errs.AuthFailed("用户信息获取失败");
  }

  ctx.body = {
    code: 200,
    data: userInfo,
  };
});

// 更新管理员数据
router.post("/update", new Auth(32).m, async (ctx) => {
  const { power, account, admin_id, ...admin } = ctx.request.body;

  if (admin.avatar) {
    const adminInfo = await Admin.findOne({ where: { admin_id } });
    await Alioss.del(adminInfo.avatar);
  }
  const updatedInfo = await Admin.update(admin, {
    where: {
      admin_id,
    },
  });

  if (!updatedInfo) {
    throw new global.errs.AuthFailed("用户信息更新失败");
  }

  ctx.body = {
    code: 200,
    msg: "更新成功",
  };
});

router.post("/del", new Auth(32).m, async (ctx) => {
  const { uid } = ctx.request.body;
  const admin = await Admin.destroy({
    where: {
      id: uid,
    },
    force: true,
  });

  if (!admin) {
    throw new global.errs.AuthFailed("删除失败");
  }

  ctx.body = {
    code: 200,
    msg: "删除成功",
  };
});

router.post("/list", new Auth(32).m, async (ctx, next) => {
  const { page = 1, pageSize = 10 } = ctx.request.body;
  const offset = (page - 1) * pageSize;

  const { count: total, rows } = await Admin.findAndCountAll({
    limit: pageSize, // 每页数量
    offset, // 偏移量
    order: [["admin_id", "ASC"]], // 排序
  });

  ctx.body = {
    code: 200,
    msg: "获取成功",
    total,
    data: rows,
  };
});

module.exports = router;
